package com.poem.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.poem.constant.MessageConstant;
import com.poem.context.BaseContext;
import com.poem.dto.LoginDTO;
import com.poem.dto.RegisterDTO;
import com.poem.entity.Users;
import com.poem.exception.BaseException;
import com.poem.mapper.AuthMapper;
import com.poem.mapper.FavoritesMapper;
import com.poem.result.Result;
import com.poem.service.AuthService;
import com.poem.utils.PasswordUtil;
import com.poem.vo.LoginInfo;
import jakarta.annotation.Resource;
import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @ClassName: AuthServiceImpl
 * @Author: YLY
 * @Description:
 * @Date: 2025/10/21
 * @Version: 1.0
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private AuthMapper authMapper;
    @Resource
    private FavoritesMapper favoritesMapper;

    public LoginInfo login(LoginDTO loginDTO) {
        // 先根据用户名查询用户是否存在
        String userByUsername = authMapper.getUserByUsername(loginDTO.getUsername());

        LoginInfo loginInfo = new LoginInfo();
        if (userByUsername == null) {
            // 用户不存在
            loginInfo.setLoginStatus(-1);
            return loginInfo;
        }

        // 用户存在，先根据用户名获取用户信息
        Users user = authMapper.getUserByUsernameAll(loginDTO.getUsername());
        // 使用BCrypt验证密码
        if (user != null && PasswordUtil.matches(loginDTO.getPassword(), user.getPassword())) {
            // 用户名和密码都正确
            BeanUtils.copyProperties(user, loginInfo);
            loginInfo.setPassword(null); // 不返回密码信息
            loginInfo.setLoginStatus(1); // 登录成功
            return loginInfo;
        }

        // 用户存在但密码错误
        loginInfo.setLoginStatus(0);
        return loginInfo;
    }

    /**
     * 删除用户
     * 
     * @param username
     */
    public void deleteUser(String username) {
        // 用户注销的时候需要把相关的收藏信息全部删除
        Long userId = BaseContext.getCurrentId();
        favoritesMapper.deleteFavoritesByUserId(userId);

        authMapper.deleteUser(username);
    }

    /**
     * 添加用户
     * 
     * @param registerDTO
     */
    public void addUser(RegisterDTO registerDTO) {
        // 主动检查用户名是否已存在
        String existingUsername = authMapper.getUserByUsername(registerDTO.getUsername());
        if (existingUsername != null) {
            throw new BaseException(registerDTO.getUsername() + MessageConstant.ACCOUNT_ALREADY_EXISTS);
        }

        Users user = new Users();
        BeanUtils.copyProperties(registerDTO, user);
        // 对密码进行加密处理
        user.setPassword(PasswordUtil.encodePassword(registerDTO.getPassword()));
        authMapper.addUser(user);
    }

    /**
     * 获取当前用户
     * 
     * @return
     */
    public Users getCurrentUser() {

        Long userId = BaseContext.getCurrentId();
        return authMapper.getCurrentUser(userId);
    }

}